﻿using System.Web;

namespace MetaSapiens.PageMethods
{
	/// <summary>
	/// Базовый класс хэндлнра с поддержкой page methods
	/// </summary>
	public class BaseHandler : IHttpHandler
	{
		/// <summary>
		/// Контекст запроса
		/// </summary>
		public HttpContext Context { get; private set; }

		/// <summary>
		/// Признак, что нужно обрабатывать default page method
		/// </summary>
		private readonly bool handleDefaultMethod;

        /// <summary>
        /// Признак, что нужно автоматически обрабатывать все запросы
        /// </summary>
        private readonly bool autoProcessRequest;

		/// <summary>
		/// Initializes a new instance of the <see cref="BaseHandler"/> class.
		/// </summary>
		public BaseHandler() : this(false)
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="BaseHandler"/> class.
		/// </summary>
		public BaseHandler(bool handleDefaultMethod) : this(handleDefaultMethod, true)
		{
		}

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseHandler"/> class.
        /// </summary>
        /// <param name="handleDefaultMethod">Обрабатывать PageMethod по умолчанию</param>
        /// <param name="autoProcessRequest">Автоматически обрабатывать все запросы</param>
        public BaseHandler(bool handleDefaultMethod, bool autoProcessRequest)
		{
			this.handleDefaultMethod = handleDefaultMethod;
            this.autoProcessRequest = autoProcessRequest;
		}


		#region Implementation of IHttpHandler

		/// <summary>
		/// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. 
		/// </param>
		public void ProcessRequest(HttpContext context)
		{
			Context = context;

            if (autoProcessRequest)
            {
                PageMethodsEngine.InvokeMethod(GetType(), this, handleDefaultMethod);
            }
		}

		/// <summary>
		/// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
		/// </summary>
		/// <returns>
		/// true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
		/// </returns>
		public virtual bool IsReusable
		{
			get { return false; }
		}

		#endregion
	}
}
